package com.woniu.login.configuration;

import com.woniu.common.entity.AdmEmployee;
import com.woniu.login.service.LoginService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.context.annotation.Configuration;

@Configuration
public class JWTShiroRealm extends AuthorizingRealm {

    protected LoginService loginService;

    public JWTShiroRealm(LoginService loginServicee){
        System.out.println("JWTShiroRealm初始化");
        this.loginService = loginServicee;
        //  JWTShiroRealm使用自定义凭证匹配器
        this.setCredentialsMatcher(new JWTCredentialsMatcher());
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        System.out.println("supports："+token);
        //  判断JWTToken类型
        return token instanceof JWTToken;
    }

    /**
     * 认证信息.(身份验证) : Authentication 是用来验证用户身份
     * 默认使用此方法进行用户名正确与否验证，错误抛出异常即可。
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
        System.out.println("authcToken："+authcToken);
        //  获取JWTtoken(token,host)
        JWTToken jwtToken = (JWTToken) authcToken;
        String token = jwtToken.getToken();
        //  根据JWT获取用户信息
        AdmEmployee admEmployee = loginService.getJwtTokenInfo(JwtUtils.getUsername(token));
        System.out.println("JWT："+admEmployee);
        if(admEmployee == null)
            throw new AuthenticationException("token过期，请重新登录");
        //  返回认证信息
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(admEmployee, 12345, "jwtRealm");
        return authenticationInfo;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return new SimpleAuthorizationInfo();
    }
}
